/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.standarcloud.security.gateway.convert;

import com.alibaba.fastjson.JSON;
import com.hyts.standarcloud.security.gateway.model.SecurityAuthentication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.server.authentication.ServerFormLoginAuthenticationConverter;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * @project-name:standard-cloud
 * @package-name:com.hyts.standarcloud.security.gateway.convert
 * @author:LiBo/Alex
 * @create-date:2020-03-29 22:11
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
@Slf4j
public class SecurityAuthenticationConverter extends ServerFormLoginAuthenticationConverter {

    @Override
    public Mono<Authentication> convert(ServerWebExchange exchange) {
        //从session中获取登陆用户信息
        String value = exchange.getSession().block().getAttribute("AccountInfo");
        if(value == null) {
            log.error("用户认证信息为空,返回获取认证信息失败");
            return Mono.empty();
        } else {
            List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
            //获取权限信息
            List<String> roles = JSON.parseObject(value).getJSONArray("roles").toJavaList(String.class);
            roles.forEach(role->{
                //这里必须添加前缀，参考：AuthorityReactiveAuthorizationManager.hasRole(role)
                SimpleGrantedAuthority auth = new SimpleGrantedAuthority("ROLE_" + role);
                simpleGrantedAuthorities.add(auth);
            });
            //添加用户信息到spring security之中。
            SecurityAuthentication  xinyueAccountAuthentication = new SecurityAuthentication(null, value, simpleGrantedAuthorities);
            return Mono.just(xinyueAccountAuthentication);
        }
    }
}
